﻿using System;
using System.Text;
using PostSharp.Aspects;

//[assembly: CalculateTime(AspectPriority = 1)]

namespace Framework.Common.AOP.Performance
{
    /// <summary>
    /// 计算方法时间
    /// </summary>
    [Serializable]
    public sealed class TimeAttribute : OnMethodBoundaryAspect
    {
        public TimeAttribute()
            : this(0)
        {
        }

        public TimeAttribute(double tick)
        {
            timeTick = tick;
            timeBuilder = new StringBuilder();
        }

        private readonly StringBuilder timeBuilder;
        private readonly double timeTick;
        private DateTime timePoint;

        public override void OnEntry(MethodExecutionArgs eventArgs)
        {
            timeBuilder.Clear();
            timeBuilder.Append("\n\r方法名称:");
            timeBuilder.Append(Formatter.Format(eventArgs));
            timePoint = DateTime.Now;
        }

        public override void OnExit(MethodExecutionArgs eventArgs)
        {
            var timeSpan = (DateTime.Now - timePoint).TotalMilliseconds;
            if (timeTick <= 0 || timeSpan > timeTick)
            {
                timeBuilder.Append("\n\r耗时:");
                timeBuilder.Append(timeSpan.ToString("N0"));
                timeBuilder.Append("ms\n\r");
                LogHelper.Debug(timeBuilder);
            }
        }
    }
}
